#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from Lib import Infos, Exec

def checkMemory():
    '''
    Return free memory , total memory , buffer size, and cache size (in Mo) of the server
    '''
    rawmemory = Exec.runCmd('free -m | grep Mem:')[1][0][:-1].split()
    return([rawmemory[3], rawmemory[1], rawmemory[5], rawmemory[6]])

def checkDiskSpace():
    '''
    Return name, mountpoint, used space, total space and percent used for each partitions
    '''
    diskspace = []
    for i in Infos.getParts():
        if Exec.runCmd('mount | grep ' + i)[1][0] != '':
            tmp = Exec.runCmd('df -h | grep ' + i)[1][0].split()
            diskspace.append((i, tmp[5], tmp[2], tmp[1], tmp[4]))
    return(diskspace)

def checkSmartStatus():
    '''
    Return the name and the smart status of all ATA disks
    '''
    smartstatus = []
    status = {0: 'Everything is OK',
                        1: 'Device open failed',
                        2: 'Some SMART command to the disk failed',
                        3: 'SMART status check returned "DISK FAILING"',
                        4: 'We found prefail attributes <= threshold',
                        5: 'Some attributes have been <= threshold in the past',
                        6: 'The device error log contains records of errors',
                        7: 'The device self-test log contains records of errors'}
    for i in Infos.getDisks():
        output = Exec.runCmd('smartctl -q -a ' + i)[0]
        if status.has_key(output):
            smartstatus.append((i, status[output]))
        else:
            smartstatus.append((i, 'Unidentified smart return code'))
    return(smartstatus)

def ckeckServicesStatus():
    '''
    Return the name of all services launched at startup (archlinux only)
    '''
    servicesstatus = []
    for i in Infos.getServices():
        if Exec.Runcmd('ps aux | grep ' + i + ' | grep -v grep')[1][0] != '':
            servicesstatus.append((i, 'started'))
        else:
            servicesstatus.append((i, 'stopped'))
    return(servicesstatus)
